﻿using System.Collections;
using System.Collections.Generic;
using System.Xml;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using System.IO;
using DG.Tweening;
using UnityEngine.Video;
using Random = UnityEngine.Random;

public class Config : MonoBehaviour
{
    public static Config Instance;
    public PaintView paintView; //绘画主面板
    public RawImage bgRawimage; //背景图片或视频
    public RawImage reWriteRawImage; //重写按钮
    public RawImage sureRawImage; //确定按钮
    public RawImage signatureRawImage; //签名版背景
    public int maxCircle; //显示签名个数
    public float circleScale; //签名大小
    public Color brushColor;
    public RectTransform paintRect; //绘画区域大小及位置设置

    public List<Texture> circles = new List<Texture>();
    public List<RectTransform> childs = new List<RectTransform>();

    protected virtual IEnumerator Start()
    {
        Instance = this;
        yield return StartCoroutine(ReadXML());
        yield return StartCoroutine(LoadPhoto(Application.streamingAssetsPath +
                                              "/确认按钮/确认.png", sureRawImage));
        yield return StartCoroutine(LoadPhoto(Application.streamingAssetsPath +
                                              "/重写按钮/重写.png", reWriteRawImage));
        yield return StartCoroutine(LoadPhoto(Application.streamingAssetsPath +
                                              "/签名板背景/0.png", signatureRawImage));
        yield return StartCoroutine(LoadTextures());
    }

    // 读取xml配置
    private IEnumerator ReadXML()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("file://" + Application.streamingAssetsPath + "/config.xml");
        yield return doc;

        float brushSize = float.Parse(doc.SelectSingleNode("//BrushSize").InnerText);
        int colorSelect = int.Parse(doc.SelectSingleNode("//ColorSelect").InnerText);
        maxCircle = int.Parse(doc.SelectSingleNode("//MaxCircle").InnerText);
        circleScale = float.Parse(doc.SelectSingleNode("//CircleScale").InnerText);
        bool isVideo = doc.SelectSingleNode("//isVideo").InnerText == "true";
        if (isVideo)
        {
            VideoPlayer videoPlayer = bgRawimage.transform.GetChild(0).GetComponent<VideoPlayer>();
            videoPlayer.GetComponent<RawImage>().DOFade(1, 1);
            videoPlayer.url = "file://" + Application.streamingAssetsPath + "/BackGround/bg.mp4";
            videoPlayer.Play();
        }
        else
        {
            StartCoroutine(LoadPhoto(Application.streamingAssetsPath +
                                     "/BackGround/bg.jpg", bgRawimage));
        }

        float offsetX = float.Parse(doc.SelectSingleNode("//offsetX").InnerText);
        float offsetY = float.Parse(doc.SelectSingleNode("//offsetY").InnerText);
        string paintScale = doc.SelectSingleNode("//paintScale").InnerText;
        Vector2 vector = new Vector2(float.Parse(paintScale.Split(',')[0]), float.Parse(paintScale.Split(',')[1]));
        paintRect.localPosition = new Vector3(offsetX, offsetY);
        paintRect.localScale = vector;

        //string signaturePath = doc.SelectSingleNode("//SignaturePath").InnerText;
        //bool isHex = doc.SelectSingleNode("//isHex").InnerText == "true";

        switch (colorSelect)
        {
            case 0:
                brushColor = Color.black;
                break;
            case 1:
                brushColor = Color.white;
                break;
            case 2:
                brushColor = Color.red;
                break;
            case 3:
                brushColor = Color.green;
                break;
            case 4:
                brushColor = Color.yellow;
                break;
            case 5:
                brushColor = Color.grey;
                break;
            default:
                brushColor = Color.black;
                break;
        }

        // Debug.Log(brushSize + "@@" + colorSelect);
        paintView.InitData(brushSize, brushColor);
    }

    /// <summary>
    /// 如果背景是图片则加载图片
    /// </summary>
    /// <param name="filePath"></param>
    /// <param name="rawImage"></param>
    /// <returns></returns>
    private IEnumerator LoadPhoto(string filePath, RawImage rawImage)
    {
        UnityWebRequest request = UnityWebRequestTexture.GetTexture("file://" + filePath);
        yield return request.SendWebRequest();
        if (!string.IsNullOrEmpty(request.error))
        {
            Debug.LogError(request.error);
        }
        else
        {
            Texture texture = DownloadHandlerTexture.GetContent(request);
            rawImage.texture = texture;
        }
    }

    /// <summary>
    /// 加载气泡图片
    /// </summary>
    /// <returns></returns>
    IEnumerator LoadTextures()
    {
        foreach (var item in Directory.GetFiles(Application.streamingAssetsPath + "/气泡图片", "*.png"))
        {
            UnityWebRequest request = UnityWebRequestTexture.GetTexture("file://" + item);
            yield return request.SendWebRequest();
            if (!string.IsNullOrEmpty(request.error))
            {
                Debug.LogError(request.error);
            }
            else
            {
                Texture texture = DownloadHandlerTexture.GetContent(request);
                circles.Add(texture);
            }
        }

        yield return new WaitForEndOfFrame();
        StartCoroutine(LoadTexturesOfPaints());
    }

    IEnumerator LoadTexturesOfPaints()
    {
        string[] dirs = Directory.GetFiles(Application.streamingAssetsPath + "/Pics", "*.png");
        for (int i = dirs.Length - 1; i >= 0; i--)
        {
            if (childs.Count >= maxCircle)
            {
                break;
            }
            // Debug.Log($"{i}-{childs.Count}-{maxCircle}");

            UnityWebRequest request = UnityWebRequestTexture.GetTexture("file://" + dirs[i]);
            yield return request.SendWebRequest();
            if (!string.IsNullOrEmpty(request.error))
            {
                Debug.LogError(request.error);
            }
            else
            {
                Texture texture = DownloadHandlerTexture.GetContent(request);
                yield return StartCoroutine(LoadOldPaints(texture));
                yield return new WaitForSeconds(1);
            }
        }

        FindObjectOfType<GraphicRaycaster>().enabled = true;
    }

    //加载旧签名
    public virtual IEnumerator LoadOldPaints(Texture oldTexture)
    {
        Vector3 vector3 = new Vector3(Random.Range(-Screen.width / 2 + 50, Screen.width / 2 - 50),
            Random.Range(-Screen.height / 2 + 50, Screen.height / 2 - 50));
        Debug.Log("实例化存储图片：" + vector3);
        RectTransform rect = Instantiate(Resources.Load<RectTransform>("Image"), Vector3.zero,
            Quaternion.identity, paintView.ImagePool);
        rect.localPosition = vector3;
        rect.DOScale(circleScale, 1);
        rect.GetComponent<RawImage>().texture = circles[Random.Range(0, circles.Count)];
        rect.GetComponent<Rigidbody2D>().AddForce(new Vector2(
            Random.Range(-1f, 1f), Random.Range(-1f, 1f)) * Random.Range(100, 150), ForceMode2D.Impulse);
        GameObject obj = new GameObject("oldPic");
        obj.AddComponent<RectTransform>().SetParent(rect);
        obj.GetComponent<RectTransform>().localPosition = Vector3.zero;
        obj.GetComponent<RectTransform>().localScale = Vector3.one * 0.8f;
        obj.GetComponent<RectTransform>().sizeDelta = new Vector2(270, 180);
        obj.AddComponent<RawImage>().texture = oldTexture;
        childs.Add(rect);
        yield return null;
    }

    public void CheckNum()
    {
        if (childs.Count > maxCircle)
        {
            childs[0].DOScale(0, 1).OnComplete(() =>
            {
                Destroy(childs[0].gameObject);
                childs.RemoveAt(0);
            });
        }
    }
}
